﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Outlook.WorkItems.Extension.Controls;
using Outlook.WorkItems.Extension.Manager.TeamPortal;
using Attachment = Microsoft.Office.Interop.Outlook.Attachment;
using Exception = System.Exception;

namespace Outlook.WorkItems.Extension.Addin.Forms
{
    internal partial class UploadAttachmentsForm : Form
    {
        private readonly WorkItemStore _store;
        private readonly string _projectName;

        public UploadAttachmentsForm()
        {
            InitializeComponent();

            teamTreeViewUC1.ShowReport = false;
            teamTreeViewUC1.ShowDocumentLibrairies = true;
            teamTreeViewUC1.InitTreeView();
        }

        public UploadAttachmentsForm(WorkItemStore store, string projectName, Attachments attachments)
            : this()
        {
            _store = store;
            try
            {
                _projectName = projectName;
                Text += string.Format(" - {0}", _projectName);

                foreach (Attachment item in attachments)
                {
                    if (item.Type != OlAttachmentType.olByValue) 
                        continue;

                    var lvi = new ListViewItem(item.DisplayName);
                    var extension = item.DisplayName.Substring(item.DisplayName.LastIndexOf("."), item.DisplayName.Length - item.DisplayName.LastIndexOf("."));
                    lvi.ImageIndex = IconsCache.GetIconIndex(fileExtensionImageList, extension);
                    lvi.Tag = item;
                    var lvsi = new ListViewItem.ListViewSubItem(lvi, ((double)item.Size/1024f).ToString("0 KB"));
                    lvi.SubItems.Add(lvsi);
                    listView1.Items.Add(lvi);
                }
            }
            catch (Exception ex)
            {
                using (var frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
        }

        public UploadAttachmentsForm(IEnumerable<Attachment> attachments)
            : this()
        {
            try
            {
                foreach (var item in attachments)
                {
                    if (item.Type != OlAttachmentType.olByValue) 
                        continue;

                    var lvi = new ListViewItem(item.DisplayName);
                    var extension = item.DisplayName.Substring(item.DisplayName.LastIndexOf("."), item.DisplayName.Length - item.DisplayName.LastIndexOf("."));
                    lvi.ImageIndex = IconsCache.GetIconIndex(fileExtensionImageList, extension);
                    lvi.Tag = item;
                    var lvsi = new ListViewItem.ListViewSubItem(lvi, ((double)item.Size / 1024f).ToString("0 KB"));
                    lvi.SubItems.Add(lvsi);
                    listView1.Items.Add(lvi);
                }
            }
            catch (Exception ex)
            {
                using (var frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }

        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                var selectedNode = teamTreeViewUC1.treeView1.SelectedNode;
                DocumentLibrairyNode librairieNode;
                if (selectedNode is FolderNode)
                {
                    librairieNode = ((FolderNode)selectedNode).DocumentLibrairyNode;
                }
                else if (selectedNode is DocumentLibrairyNode)
                {
                    librairieNode = selectedNode as DocumentLibrairyNode;
                }
                else
                    return;

                var teamProjectNode = librairieNode.TeamProjectNode;

                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectNode.Favorite.TeamServerUri));

                var registration = (IRegistration)tfs.GetService(typeof(IRegistration));

                var entries = registration.GetRegistrationEntries(RegistrationUtilities.SharePointName);

                string baseSiteUrl = null;
                foreach (var si in entries[0].ServiceInterfaces.Where(si => si.Name == "BaseSiteUrl"))
                {
                    baseSiteUrl = si.Url;
                }

                var projectBaseUrl = baseSiteUrl + "/" + teamProjectNode.Tag;
                
                foreach (ListViewItem lvi in listView1.Items)
                {
                    if (lvi.Checked != true) 
                        continue;

                    var att = lvi.Tag as Attachment;
                    if (att == null) 
                        continue;

                    var path = Path.Combine(Path.GetTempPath(), att.FileName);

                    att.SaveAsFile(path);

                    string destinationPath = null;
                    if (selectedNode is FolderNode)
                    {
                        var fullName = selectedNode.Tag.ToString();
                        if (fullName.StartsWith(teamProjectNode.Favorite.TeamProjectName))
                        {
                            fullName = fullName.Substring(teamProjectNode.Favorite.TeamProjectName.Length + 1, fullName.Length - teamProjectNode.Favorite.TeamProjectName.Length - 1);
                        }
                        destinationPath = projectBaseUrl + "/" + fullName + "/" + att.FileName;
                    }
                    else if (selectedNode is DocumentLibrairyNode)
                    {
                        var viewUrl = selectedNode.Tag.ToString();
                        viewUrl = viewUrl.Substring(viewUrl.IndexOf('/', 7) + 1, viewUrl.LastIndexOf("/Forms") - viewUrl.IndexOf('/', 7) - 1);
                        if (viewUrl.StartsWith(teamProjectNode.Favorite.TeamProjectName))
                        {
                            viewUrl = viewUrl.Substring(teamProjectNode.Favorite.TeamProjectName.Length + 1, viewUrl.Length - teamProjectNode.Favorite.TeamProjectName.Length - 1);
                        }
                        destinationPath = projectBaseUrl + "/" + viewUrl + "/" + att.FileName;
                    }

                    if (string.IsNullOrEmpty(destinationPath)) 
                        continue;

                    var properties = new Dictionary<string, object> {{"Title", att.FileName}};

                    DocLibHelper.Upload(destinationPath, File.ReadAllBytes(path), properties);
                }
            }
            catch (Exception ex)
            {
                using (var frm = new ErrorForm(ex))
                {
                    frm.ShowDialog();
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems == null || listView1.SelectedItems.Count != 1) 
                return;

            var att = listView1.SelectedItems[0].Tag as Attachment;
            if (att == null) 
                return;

            var path = Path.Combine(Path.GetTempPath(), att.FileName);

            att.SaveAsFile(path);

            Process.Start(path);
        }
    }
}
